package com.uam.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uam.common.annotation.Log;
import com.uam.common.config.UAMConfig;
import com.uam.common.exception.CustomException;
import com.uam.db.model.entity.DataRecord;
import com.uam.service.IDataRecordService;
import com.uam.utils.CsvUtil;
import com.uam.utils.DateUtils;
import com.uam.utils.StringUtils;
import com.uam.utils.file.analysis.File2GeoJsonUtil;
import com.uam.utils.file.analysis.help.RetAnalysisVo;
import com.uam.web.common.model.BusinessType;
import com.uam.web.common.model.PageData;
import com.uam.web.common.model.Result;
import com.uam.web.common.utils.FileUploadUtils;
import com.uam.web.common.utils.MimeTypeUtils;
import com.uam.web.common.utils.ResourceUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 数据记录Controller
 *
 * @author uam
 * @date 2023-11-22
 */
@Controller
@RequestMapping("/data/record")
@Api(tags = "数据管理")
public class DataRecordController extends BaseController {
    private String prefix = "system/record";

    @Autowired
    private IDataRecordService dataRecordService;
    @Autowired
    private UAMConfig uamConfig;

    /**
     * 查询数据记录列表
     */
    @Log(title = "查看数据列表", businessType = BusinessType.QUERY_LOG)
    @ApiOperation(value = "查看数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token" , value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "queryLog" , value = "查询是否生成日志，1：生成", paramType = "header"),
            @ApiImplicitParam(name = "pageNum" , value = "当前页"),
            @ApiImplicitParam(name = "pageSize" , value = "分页条数"),
            @ApiImplicitParam(name = "dataName", value = "数据名称"),
            @ApiImplicitParam(name = "dataTypeList", value = "数据类型 1:点 2:线 3:面，多个时以,隔开")
    })
    @PostMapping("/list")
    @ResponseBody
    public Result<PageData<DataRecord>> list(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam(required = false) String dataName, @RequestParam(required = false) String dataTypeList) {
        DataRecord dataRecord = new DataRecord();
        dataRecord.setDataName(dataName);
        if (!StringUtils.isEmpty(dataTypeList)) {
            dataRecord.setDataTypeList(StringUtils.splitComma(dataTypeList));
        }
        Page<DataRecord> page = new Page(pageNum, pageSize);
        IPage<DataRecord> pageResult = dataRecordService.selectDataRecordList(page, dataRecord);
        return okPageData(pageResult);
    }

    /**
     * 数据记录添加
     */
    @Log(title = "数据添加", businessType = BusinessType.INSERT)
    @ApiOperation(value = "数据添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token" , value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "dataName", value = "数据名称"),
            @ApiImplicitParam(name = "dataBak", value = "数据备份 1:是 0:否"),
            @ApiImplicitParam(name = "file", value = "上传文件")
    })
    @PostMapping("/add")
    @ResponseBody
    public Result uploadFile(@RequestPart(value = "file") MultipartFile file, @RequestParam String dataName,
                                 @RequestParam Integer dataBak) {
        try {
            // 上传并返回新文件名称
            String fileUrl = FileUploadUtils.upload(uamConfig.getUploadpath(), file, MimeTypeUtils.DATA_RECORD_ALLOWED_EXTENSION);
            String fileName = new File(fileUrl).getName();
            RetAnalysisVo analysis = File2GeoJsonUtil.analysis(fileUrl, uamConfig.getGeopath(), fileName);
            if (analysis == null) {
                return Result.fail("文件上传失败");
            }

            DataRecord dataRecord = new DataRecord();
            dataRecord.setDataId(UUID.randomUUID().toString());
            dataRecord.setDataType(analysis.getDataType());
            dataRecord.setDataName(dataName);
            dataRecord.setDataBak(dataBak);
            dataRecord.setDataUrl(analysis.getDataUrl());
            dataRecord.setDataSize(analysis.getDataSize());
            dataRecord.setDataFormat(analysis.getFileType());
            dataRecord.setDisplay(1);
            dataRecord.setCreateName(getLoginName());
            return toResult(dataRecordService.insertDataRecord(dataRecord));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改保存数据记录
     */
    @Log(title = "数据重命名", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "数据重命名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token" , value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "数据唯一标识，修改、重命名、删除记录时必传"),
            @ApiImplicitParam(name = "dataName", value = "数据名称"),
    })
    @PostMapping("/edit")
    @ResponseBody
    public Result edit(@RequestParam Long id, @RequestParam String dataName) {
        if (id == null || StringUtils.isEmpty(dataName)) {
            return Result.paramError("");
        }
        DataRecord dataRecord = new DataRecord();
        dataRecord.setId(id);
        dataRecord.setDataName(dataName);
        return toResult(dataRecordService.updateDataRecord(dataRecord));
    }

    /**
     * 修改保存数据记录
     */
    @Log(title = "数据删除", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "数据删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token" , value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "数据唯一标识，修改、重命名、删除记录时必传"),
    })
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestParam Long id) {
        if (id == null) {
            return Result.paramError("");
        }
        DataRecord dataRecord = new DataRecord();
        dataRecord.setId(id);
        dataRecord.setDisplay(0);
        return toResult(dataRecordService.updateDataRecord(dataRecord));
    }

    /**
     * 数据详情
     */
    @Log(title = "数据详情", isSaveResponseData = false)
    @ApiOperation(value = "数据详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "数据ID"),
    })
    @PostMapping("/detail")
    @ResponseBody
    public Result<DataRecord> detail(@RequestParam Long id) {
        if (id == null) {
            return Result.paramError("");
        }
        DataRecord dataRecord = dataRecordService.selectDataRecordById(id);
        if (dataRecord == null) {
            return Result.fail("数据ID有误");
        }
        String fileContent = ResourceUtils.getFileContent(dataRecord.getDataUrl());
        dataRecord.setContent(JSON.parse(fileContent));
        return Result.ok(dataRecord);
    }

    @PostMapping("/export")
    @ResponseBody
    @ApiOperation(value = "数据导出geojson")
    public void export(HttpServletResponse response, @RequestParam(required = false) Long id) throws IOException {
        if (id == null) {
            throw new CustomException("id 不能为空！");
        }
        DataRecord dataRecord = dataRecordService.selectDataRecordById(id);
        if (dataRecord == null) {
            throw new CustomException("数据ID有误！");
        }
        String fileContent = ResourceUtils.getFileContent(dataRecord.getDataUrl());
        CsvUtil.createJSONFile(fileContent, dataRecord.getDataName()+"-"+ DateUtils.getHHMMSS()+".geojson", response);
    }
}
